package com.example.springdocdemo.rest;

import com.example.springdocdemo.server.SSEService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Controller
@RequestMapping("/sse")
public class SSeTestController {

    private static final Map<String, Boolean> SEND_MAP = new ConcurrentHashMap<>();

    @Autowired
    private SSEService sseService;

    @GetMapping("/createSse")
    @CrossOrigin
    public SseEmitter createSse(String uid) {
        return sseService.crateSse(uid);
    }

    @GetMapping("/sendMsg")
    @ResponseBody
    @CrossOrigin
    public SseEmitter sendMsg(@RequestParam("uid") String uid) throws InterruptedException {
        SseEmitter sseEmitter = sseService.crateSse(uid);
        if (SEND_MAP.get(uid) == null || !SEND_MAP.get(uid)) {
            new Thread(() -> {
                int i = 0;
                while (true) {
                    try {
                        i++;
                        String message = "uid:" + uid + " number:" + i + " message:" + UUID.randomUUID().toString().replace("-", "");
                        sseService.sendMessage(uid, "消息" + i, message);
                        SEND_MAP.put(uid, true);
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        closeSse(uid);
                    }
                }
            }).start();
        }
        return sseEmitter;
    }

    @GetMapping("/closeSse")
    @CrossOrigin
    public void closeSse(String uid) {
        sseService.closeSse(uid);
    }
}
